import {Component, OnInit} from '@angular/core';
import {Observable} from "rxjs";
import {ApiService} from "../shared/api.service";
import {HttpClient} from "@angular/common/http";
import {AuthService} from "../core/auth.service";

@Component({
  selector: 'oidc-app-home',
  templateUrl: 'home.html',
  styles: [
  ]
})
export class HomeComponent implements OnInit {
  apiResponse!: Observable<string>;

  isAuthenticated$: Observable<boolean>;
  isDoneLoading$: Observable<boolean>;
  canActivateProtectedRoutes$: Observable<boolean>;

  constructor(private apiService: ApiService, private http: HttpClient,private authService: AuthService) {
    this.isAuthenticated$ = this.authService.isAuthenticated$;
    this.isDoneLoading$ = this.authService.isDoneLoading$;
    this.canActivateProtectedRoutes$ = this.authService.canActivateProtectedRoutes$;
  }

  ngOnInit(): void {
    // this.http.get('http://127.0.0.1:9000/test')  // test  .well-known/openid-configuration
    //   .subscribe(
    //     data => {
    //       // 成功响应，data是返回的数据
    //       console.log('访问9000 cors 成功 Data received: ', data);
    //       // 在这里处理数据
    //     },
    //     error => {
    //       // 错误响应
    //       console.error('Error:', error);
    //       // 处理错误情况
    //     },
    //     () => {
    //       // 请求完成，无论成功或失败
    //       console.log('Request cors 成功 completed========');
    //       // 可能需要清理或关闭资源
    //     }
    //   )

    //this.apiResponse = this.apiService.getProtectedApiResponse();
  }

  login() { this.authService.login(); }
  logout() { this.authService.logout(); }
  refresh() { this.authService.refresh(); }
  reload() { window.location.reload(); }
  clearStorage() { localStorage.clear(); }

  logoutExternally() {
    window.open(this.authService.logoutUrl);
  }

  get hasValidToken() { return this.authService.hasValidToken(); }
  get accessToken() { return this.authService.accessToken; }
  get refreshToken() { return this.authService.refreshToken; }
  get identityClaims() { return this.authService.identityClaims; }
  get idToken() { return this.authService.idToken; }

  get email(): string {
    return this.authService.identityClaims
      ? (this.authService.identityClaims as any)['email']
      : '-';
  }

}
